import { BrowserWindow, screen } from 'electron';
import * as path from 'path';
import * as http from 'http';

export class WindowManager {
  private mainWindow: BrowserWindow | null = null;

  public createMainWindow(): BrowserWindow {
    const { width, height } = screen.getPrimaryDisplay().workAreaSize;

    // 创建浏览器窗口
    this.mainWindow = new BrowserWindow({
      width: Math.min(1200, width - 100),
      height: Math.min(800, height - 100),
      minWidth: 800,
      minHeight: 600,
      show: false,
      autoHideMenuBar: true,
      titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default',
      icon: path.join(__dirname, '../../assets/icons/icon.png'),
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: path.join(__dirname, '../preload/index.js'),
        webSecurity: true,
        allowRunningInsecureContent: false,
      },
    });

    // 窗口事件处理
    this.mainWindow.once('ready-to-show', () => {
      if (this.mainWindow) {
        this.mainWindow.show();
        
        // 在开发环境中居中显示窗口
        if (process.env.NODE_ENV === 'development') {
          this.mainWindow.center();
        }
      }
    });

    this.mainWindow.on('closed', () => {
      this.mainWindow = null;
    });

    this.mainWindow.on('maximize', () => {
      if (this.mainWindow) {
        this.mainWindow.webContents.send('window-maximized');
      }
    });

    this.mainWindow.on('unmaximize', () => {
      if (this.mainWindow) {
        this.mainWindow.webContents.send('window-unmaximized');
      }
    });

    this.mainWindow.on('focus', () => {
      if (this.mainWindow) {
        this.mainWindow.webContents.send('window-focused');
      }
    });

    this.mainWindow.on('blur', () => {
      if (this.mainWindow) {
        this.mainWindow.webContents.send('window-blurred');
      }
    });

    // 加载应用
    if (process.env.NODE_ENV === 'development') {
      // 尝试常见的开发端口
      const ports = [3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010];
      this.loadDevelopmentServer(ports);
    } else {
      this.mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));
    }

    return this.mainWindow;
  }

  public getMainWindow(): BrowserWindow | null {
    return this.mainWindow;
  }

  public closeMainWindow(): void {
    if (this.mainWindow) {
      this.mainWindow.close();
    }
  }

  public minimizeMainWindow(): void {
    if (this.mainWindow) {
      this.mainWindow.minimize();
    }
  }

  public maximizeMainWindow(): void {
    if (this.mainWindow) {
      if (this.mainWindow.isMaximized()) {
        this.mainWindow.unmaximize();
      } else {
        this.mainWindow.maximize();
      }
    }
  }

  public isMainWindowMaximized(): boolean {
    return this.mainWindow ? this.mainWindow.isMaximized() : false;
  }

  public reloadMainWindow(): void {
    if (this.mainWindow) {
      this.mainWindow.reload();
    }
  }

  public toggleDevTools(): void {
    if (this.mainWindow) {
      if (this.mainWindow.webContents.isDevToolsOpened()) {
        this.mainWindow.webContents.closeDevTools();
      } else {
        this.mainWindow.webContents.openDevTools();
      }
    }
  }

  private async loadDevelopmentServer(ports: number[]): Promise<void> {
    // 等待一段时间让 Vite 服务器启动
    console.log('Waiting for Vite development server to start...');
    await this.sleep(3000);

    let attempts = 0;
    const maxAttempts = 3;

    while (attempts < maxAttempts) {
      console.log(`Attempt ${attempts + 1} to find Vite development server...`);

      for (const port of ports) {
        try {
          const isRunning = await this.checkViteServerRunning(port);
          if (isRunning) {
            console.log(`Found Vite development server on port ${port}`);
            if (this.mainWindow) {
              await this.mainWindow.loadURL(`http://localhost:${port}`);
            }
            return;
          }
        } catch (error) {
          console.log(`Port ${port} is not available, trying next...`);
        }
      }

      attempts++;
      if (attempts < maxAttempts) {
        console.log('No server found, waiting 2 seconds before retry...');
        await this.sleep(2000);
      }
    }

    // 如果没有找到开发服务器，显示错误页面
    console.error('No Vite development server found, showing error page');
    this.showErrorPage();
  }

  private sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  private checkViteServerRunning(port: number): Promise<boolean> {
    return new Promise((resolve) => {
      console.log(`Checking port ${port} for Vite server...`);

      // 先尝试 IPv4 (127.0.0.1)
      this.checkPortOnHost('127.0.0.1', port).then((ipv4Result) => {
        if (ipv4Result) {
          console.log(`Port ${port} found on IPv4`);
          resolve(true);
          return;
        }

        // 如果 IPv4 没找到，尝试 IPv6 (::1)
        console.log(`Trying IPv6 for port ${port}...`);
        this.checkPortOnHost('::1', port).then((ipv6Result) => {
          if (ipv6Result) {
            console.log(`Port ${port} found on IPv6`);
            resolve(true);
          } else {
            console.log(`Port ${port} not found on either IPv4 or IPv6`);
            resolve(false);
          }
        });
      });
    });
  }

  private checkPortOnHost(host: string, port: number): Promise<boolean> {
    return new Promise((resolve) => {
      const req = http.request({
        hostname: host,
        port: port,
        path: '/',
        method: 'HEAD',
        timeout: 3000
      }, (res) => {
        console.log(`Port ${port} on ${host}: status=${res.statusCode}, contentType=${res.headers['content-type']}`);
        // 对于开发服务器，只要返回成功状态码就认为是可用的
        // 404 也是正常的，因为可能是 SPA 路由
        const isSuccessCode = res.statusCode ? res.statusCode >= 200 && res.statusCode < 500 : false;
        const isViteServer = res.statusCode === 200 || res.statusCode === 404;
        console.log(`Port ${port} on ${host} check result: ${isViteServer} (statusCode=${res.statusCode})`);
        resolve(isViteServer);
      });

      req.on('error', (error) => {
        console.log(`Port ${port} on ${host} error: ${error.message}`);
        resolve(false);
      });

      req.on('timeout', () => {
        console.log(`Port ${port} on ${host} timeout`);
        req.destroy();
        resolve(false);
      });

      req.end();
    });
  }

  private showErrorPage(): void {
    if (this.mainWindow) {
      const errorHtml = `
        <!DOCTYPE html>
        <html>
        <head>
          <title>开发服务器未找到</title>
          <style>
            body {
              font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
              display: flex;
              justify-content: center;
              align-items: center;
              height: 100vh;
              margin: 0;
              background: #f5f5f5;
            }
            .error-container {
              text-align: center;
              padding: 40px;
              background: white;
              border-radius: 8px;
              box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            h1 { color: #ff4d4f; margin-bottom: 16px; }
            p { color: #666; line-height: 1.6; }
          </style>
        </head>
        <body>
          <div class="error-container">
            <h1>开发服务器未找到</h1>
            <p>请确保 Vite 开发服务器正在运行。<br>
            你可以在另一个终端窗口中运行：<code>npm run dev:renderer</code></p>
          </div>
        </body>
        </html>
      `;
      this.mainWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(errorHtml)}`);
    }
  }
}